#include "draw.h"
#include <cstring>
using namespace std;

// 构造函数：初始化双缓冲区
drawBoard::drawBoard() : bufferSize(screenWidth * screenHeight * sizeof(int)), buffer(NULL),isDualMode(false) 
{
    // 分配与LCD显存格式相同的缓冲区（int*，4字节/像素）
    buffer = new int[screenWidth * screenHeight];
    if (buffer == NULL) {
        std::cerr << "[错误] 双缓冲内存分配失败！" << std::endl;
    }
}

// 析构函数：释放缓冲区
drawBoard::~drawBoard() 
{
    if (buffer != NULL) 
    {
        delete[] buffer;
        buffer = NULL;
    }
}

// 类外实现draw方法
void drawBoard::draw(const Board &board, Pos selectedPos) 
{
    if(buffer == NULL)
    {
        std::cout << "[错误] 双缓冲内存未初始化！" << std::endl;
        return;
    }
    // 清空缓冲区
    memset(buffer, 0, bufferSize);
    //在缓冲区绘制完整画面（背景→棋子）
    drawBoardBackground(buffer);    // 绘制背景
    // 遍历棋盘，绘制非空棋子
    for (int row = 0; row < 9; row++) 
    {
        for (int col = 0; col < 10; col++) 
        {
            // 注意：getPieceAt参数应为(row, col)，与Pos定义一致
            ChessDef::pieceID pieceId = board.getPieceAt(Pos(row, col));
            if (pieceId == ChessDef::pieceID::kong)
            {
                continue;  // 空位置不绘制
            }

            drawOnePiece(pieceId, row, col, buffer);  // 绘制棋子
        }
    }
    drawSelected(selectedPos, buffer);
    // 一次性将缓冲区数据刷新到LCD显存（消除闪烁）
    drawFunctionButtons(buffer);
    Lcd* lcd = Lcd::instance();
    memcpy(lcd->addr(), buffer, bufferSize);  // 从缓冲区拷贝到显存
}

// 实现绘制单个棋子
void drawBoard::drawOnePiece(ChessDef::pieceID pieceId, int row, int col, int *buf)
{
    std::string bmpPath;
    
    // 从ChessDef获取图片路径（使用find避免at()的越界异常）
    auto it = ChessDef::pieceBmpPaths.find(pieceId);
    if (it == ChessDef::pieceBmpPaths.end()) 
    {
        std::cout << "[错误] 未找到棋子图片路径！" << std::endl;
        return;
    }
    bmpPath = it->second;

    // 计算屏幕坐标（列→X，行→Y）
    int screenX = boardX + col * cellSize;
    int screenY = boardY + row * cellSize;

    // 调用BMP类贴图
    BMP b(bmpPath.c_str());
    b.show(buf, screenX, screenY);  // 假设show方法接收地址、X、Y
}

// 实现绘制背景
void drawBoard::drawBoardBackground(int *buf) 
{
    BMP b("./chess.bmp");  // 棋盘背景图
    b.show(buf);   // 假设背景图绘制在默认位置
}

void drawBoard::drawSelected(Pos pos, int* buf)
{
    // 忽略未选中的情况（selectedPos为(-1,-1)）
    if (pos.row == -1 || pos.col == -1) return;

    int x = boardX + pos.col * cellSize;      // 棋子左上角X
    int y = boardY + pos.row * cellSize;      // 棋子左上角Y
    const int lineLength = 15;                // 线段延伸长度
    const int lineThickness = 2;              // 线段粗细
    const int color = 0xFF0000;               // 标记颜色（红色）

    // 左上角 - 竖线
    for (int i = 0; i < lineLength; i++) 
    {
        for (int j = 0; j < lineThickness; j++) 
        {
            int px = x - j - 1;
            int py = y + i;
            int pixelPos = py * screenWidth + px;
            if (pixelPos >= 0 && pixelPos < screenWidth * screenHeight) 
                buf[pixelPos] = color;
        }
    }
    // 左上角 - 横线
    for (int i = 0; i < lineLength; i++) 
    {
        for (int j = 0; j < lineThickness; j++) 
        {
            int px = x + i;
            int py = y - j - 1;
            int pixelPos = py * screenWidth + px;
            if (pixelPos >= 0 && pixelPos < screenWidth * screenHeight) 
                buf[pixelPos] = color;
        }
    }

    // 右上角 - 竖线
    for (int i = 0; i < lineLength; i++) 
    {
        for (int j = 0; j < lineThickness; j++) 
        {
            int px = x + cellSize + j;
            int py = y + i;
            int pixelPos = py * screenWidth + px;
            if (pixelPos >= 0 && pixelPos < screenWidth * screenHeight) 
                buf[pixelPos] = color;
        }
    }
    // 右上角 - 横线
    for (int i = 0; i < lineLength; i++) 
    {
        for (int j = 0; j < lineThickness; j++) 
        {
            int px = x + cellSize - i - 1;
            int py = y - j - 1;
            int pixelPos = py * screenWidth + px;
            if (pixelPos >= 0 && pixelPos < screenWidth * screenHeight) 
                buf[pixelPos] = color;
        }
    }

    // 左下角 - 竖线
    for (int i = 0; i < lineLength; i++) 
    {
        for (int j = 0; j < lineThickness; j++) 
        {
            int px = x - j - 1;
            int py = y + cellSize - i - 1;
            int pixelPos = py * screenWidth + px;
            if (pixelPos >= 0 && pixelPos < screenWidth * screenHeight) 
                buf[pixelPos] = color;
        }
    }
    // 左下角 - 横线
    for (int i = 0; i < lineLength; i++) 
    {
        for (int j = 0; j < lineThickness; j++) 
        {
            int px = x + i;
            int py = y + cellSize + j;
            int pixelPos = py * screenWidth + px;
            if (pixelPos >= 0 && pixelPos < screenWidth * screenHeight) 
                buf[pixelPos] = color;
        }
    }

    // 右下角 - 竖线
    for (int i = 0; i < lineLength; i++) 
    {
        for (int j = 0; j < lineThickness; j++) 
        {
            int px = x + cellSize + j;
            int py = y + cellSize - i - 1;
            int pixelPos = py * screenWidth + px;
            if (pixelPos >= 0 && pixelPos < screenWidth * screenHeight) 
                buf[pixelPos] = color;
        }
    }
    // 右下角 - 横线
    for (int i = 0; i < lineLength; i++) 
    {
        for (int j = 0; j < lineThickness; j++) 
        {
            int px = x + cellSize - i - 1;
            int py = y + cellSize + j;
            int pixelPos = py * screenWidth + px;
            if (pixelPos >= 0 && pixelPos < screenWidth * screenHeight) 
                buf[pixelPos] = color;
        }
    }
}

//绘制任意BMP图片
void drawBoard::drawBmp(const std::string& imgPath, int x, int y) 
{
    BMP bmp(imgPath.c_str());
    bmp.show(buffer, x, y); // 先画到双缓冲区
    // 同步到LCD屏幕
    memcpy(Lcd::instance()->addr(), buffer, bufferSize);
}

void drawBoard::drawButton(const std::string& bmpPath, int x, int y, int* buf) 
{
    BMP bmp(bmpPath.c_str());
    // 绘制按钮到缓冲区（限制在按钮区域内，避免越界）
    if (x + BTN_WIDTH <= screenWidth && y + BTN_HEIGHT <= screenHeight) 
    {
        bmp.show(buf, x, y);
    }
}

// 绘制所有功能按钮（公开函数，在对局中调用）
void drawBoard::drawFunctionButtons(int* buf) 
{
    if (isDualMode) 
    {
        // 双机模式：仅绘制“返回菜单”按钮
        drawButton("./fanhuicaidan.bmp", BTN_MENU_X, BTN_MENU_Y, buf);
    } 
    else if(isAIMode)
    {
        // AI模式：仅绘制“返回菜单”按钮
        drawButton("./fanhuicaidan.bmp", BTN_MENU_X, BTN_MENU_Y, buf);
    }
    else 
    {
        // 单机模式：绘制所有原有按钮（保持不变）
        // 红方功能按钮
        drawButton("./huiqi.bmp", BTN_REDO_X, BTN_REDO_Y, buf);
        drawButton("./qiuhe.bmp", BTN_DRAW_X, BTN_DRAW_Y, buf);
        drawButton("./renshu.bmp", BTN_GIVEUP_X, BTN_GIVEUP_Y, buf);

        // 黑方功能按钮
        drawButton("./huiqi2.bmp", BTN_REDO2_X, BTN_REDO2_Y, buf);
        drawButton("./qiuhe2.bmp", BTN_DRAW2_X, BTN_DRAW2_Y, buf);
        drawButton("./renshu2.bmp", BTN_GIVEUP2_X, BTN_GIVEUP2_Y, buf);

        // 通用功能按钮
        drawButton("./chongxinkaijv.bmp", BTN_RESTART_X, BTN_RESTART_Y, buf);
        drawButton("./cundang.bmp", BTN_SAVE_X, BTN_SAVE_Y, buf);
        drawButton("./fanhuicaidan.bmp", BTN_MENU_X, BTN_MENU_Y, buf);
        drawButton("./tuichuyouxi.bmp", BTN_EXIT_X, BTN_EXIT_Y, buf);
    }
}
void drawBoard::setDualMode(bool mode) 
{
    isDualMode = mode;
}
void drawBoard::setAIMode(bool mode) 
{
    isAIMode = mode;
}